/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package org.moon.framework.autoconfigure.exception.domain;

import com.google.common.annotations.VisibleForTesting;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.moon.framework.autoconfigure.MoonConstants;
import org.moon.framework.autoconfigure.springmvc.response.ErrorCode;

/**
 * 框架异常
 * @author moon
 *
 */
@Getter
@Setter
@Slf4j
public class MoonException extends RuntimeException {

    private String code;
    private String msg;

    public MoonException(ErrorCode errorCode) {
        super(errorCode.getMsg());
        this.code = errorCode.getCode();
        this.msg = errorCode.getMsg();
    }

    public MoonException(String msg) {
        super(msg);
        this.code = MoonConstants.FAIL.getCode();
        this.msg = msg;
    }
    public MoonException(String code, String msg) {
        super(msg);
        this.code = code;
        this.msg = msg;
    }
    public MoonException(Exception e) {
        super(e);
        this.code = "S500";
        this.msg = e.getMessage();
    }

    public MoonException(String code, String msg, Throwable t) {
        super(msg, t);
        this.code = code;
        this.msg = msg;
    }

    public MoonException(ErrorCode errorCode, Object... params) {
        super(errorCode.getMsg());
        this.code = errorCode.getCode();
        String message = doFormat(code, errorCode.getMsg(), params);
        this.msg = message;
    }

    public MoonException(String code, String msg, Object... params) {
        super(msg);
        this.code = code;
        String message = doFormat(code, msg, params);
        this.msg = message;
    }
    /**
     * 将错误编号对应的消息使用 params 进行格式化。
     *
     * @param code           错误编号
     * @param messagePattern 消息模版
     * @param params         参数
     * @return 格式化后的提示
     */
    @VisibleForTesting
    private String doFormat(String code, String messagePattern, Object... params) {
        StringBuilder sbuf = new StringBuilder(messagePattern.length() + 50);
        int i = 0;
        int j;
        int l;
        for (l = 0; l < params.length; l++) {
            j = messagePattern.indexOf("{}", i);
            if (j == -1) {
                log.error("[doFormat][参数过多：错误码({})|错误内容({})|参数({})", code, messagePattern, params);
                if (i == 0) {
                    return messagePattern;
                } else {
                    sbuf.append(messagePattern.substring(i));
                    return sbuf.toString();
                }
            } else {
                sbuf.append(messagePattern, i, j);
                sbuf.append(params[l]);
                i = j + 2;
            }
        }
        if (messagePattern.indexOf("{}", i) != -1) {
            log.error("[doFormat][参数过少：错误码({})|错误内容({})|参数({})", code, messagePattern, params);
        }
        sbuf.append(messagePattern.substring(i));
        return sbuf.toString();
    }
}